package com.zx.zxpicture.infrstructure.api.aliyunai;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;

import com.zx.zxpicture.infrstructure.exception.BusinessException;
import com.zx.zxpicture.infrstructure.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.zx.zxpicture.infrstructure.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.zx.zxpicture.infrstructure.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.zx.zxpicture.infrstructure.common.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 阿里云扩图模型调用接口
 */
@Component
@Slf4j
public class AliYunAiApi {
    @Value("${aliYunAi.apiKey}")
    private String apiKey;

    // 创建任务地址
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";

    // 查询任务状态
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    /**
     * 创建扩图任务
     * @param createOutPaintingTaskRequest 创建扩图任务请求参数
     * @return 扩图任务响应
     */
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest) {
        HttpResponse response = null;
        try{
            if(createOutPaintingTaskRequest == null){
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "创建扩图任务请求参数不能为空");
            }

            // 将对象转换为 JSON 字符串
            String requestBody = JSONUtil.toJsonStr(createOutPaintingTaskRequest);

            // 发送 POST 请求
             response = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                    .header("Authorization", "Bearer " + apiKey)
                    //必须开启异步处理，设置为enable，因为阿里云扩图创建任务是异步的
                    .header("X-DashScope-Async", "enable")
                    .header("Content-Type", "application/json")
                    .body(requestBody)
                    .execute();
            if(!response.isOk()){
                log.error("创建扩图任务失败");
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建扩图任务失败");
            }
            CreateOutPaintingTaskResponse createOutPaintingTaskResponse = JSONUtil.toBean(response.body(), CreateOutPaintingTaskResponse.class);
            String errorCode = createOutPaintingTaskResponse.getCode();
            if(StrUtil.isNotBlank(errorCode)){
                log.error("创建扩图任务失败：errorCode:{}, errorMessage：{}",errorCode, createOutPaintingTaskResponse.getMessage());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, createOutPaintingTaskResponse.getMessage());
            }
            return createOutPaintingTaskResponse;
        }finally {
            //释放资源
            if(response != null){
                response.close();
            }
        }
    }

    /**
     * 根据任务id查询扩图结果
     * @param taskId 任务id
     * @return 扩图结果
     */
    public GetOutPaintingTaskResponse getOutPaintingTask(String taskId) {
        HttpResponse response = null;
        try {
            //任务id不能为空
            if(StrUtil.isBlank(taskId)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "任务id不能为空");
            }
            //构造url
            String url = String.format(GET_OUT_PAINTING_TASK_URL, taskId);

            // 发送 GET 请求查询任务状态
            response = HttpRequest.get(url)
                    .header("Authorization", "Bearer " + apiKey) // 设置认证头
                    .execute();
            if(!response.isOk()){
                log.error("查询扩图任务失败");
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询扩图任务失败");
            }
            return JSONUtil.toBean(response.body(), GetOutPaintingTaskResponse.class);
        } finally {
            //释放资源
            if(response != null){
                response.close();
            }
        }
    }
}
